import * as React from 'react';
import {observer} from 'mobx-react';

import {Button, Form, Spin, message, notification} from 'antd';
import {withWrapper} from '../../components/basic';
import dataFormTab from '../../components/basic/item';
import SafeCodeModal from '../../components/safecode-modal';
import {editForm} from './form';
import UserStore from './store';

import './style.less'

const FormItem = Form.Item;

@observer
class Edit extends React.Component<any> {

    public state: any = {
        formItems: []
    }

    public formList: any = {
        avatar: {
            url: '',
            handleChange: (file: any): void => {
                console.log(file)
            },
            action: ''
        }
    }


    public async componentWillMount() {
        const {match} = this.props;
        const userId: string = match.params.user_id;


        if (!userId) {
            return notification['error']({
                message: '异常错误',
                description: '当前的用户id异常，请重新从列表进入',
                onClose: () => {
                    this.props.history.goBack();
                }
            });
        }

        await this.getDetails(userId);

    }

    /**
     * 获取详情
     * @param id
     */
    public getDetails = async (id: string) => {

        // 如果id存在  进行查询
        const result: any = await UserStore.getDetails(id);

        if (result) {
            return message.error(result);
        }

        // 循环添加参数
        for (const key in UserStore.details) {
            if (UserStore.details.hasOwnProperty(key)) {
                this.formList[key] = UserStore.details[key];
            }
        }

        // 设置封面信息
        this.formList.avatar = {
            url: this.formList.avatar,
            handleChange: (file: any): void => {
                console.log(file)
            },
            action: ''
        }

        this.setFormItems();
    }

    /**
     * 设置表单列表
     */
    public setFormItems = () => {
        const {form} = this.props;

        const Comps = dataFormTab(editForm(this.formList));

        const formItems: any[] = [];

        Object.keys(Comps).forEach((ItemName: any) => {
            const ItemComp = Comps[ItemName];

            formItems.push(
                <ItemComp initialValue={UserStore.details[ItemName]}
                          style={{width: 350}}
                          form={form}
                          key={ItemName}/>
            )
        });

        this.setState({formItems});

    }

    /**
     * 提交时
     */
    public handleSubmit = async (e: any) => {
        e.preventDefault();

        UserStore.setVisible(true);

    };
    public handleSafeCode = (safeCode: string) => {

        const {form} = this.props;

        form.validateFields(async (err: any, values: any) => {

            if (!err) {
                values.safeCode = safeCode;
                values.id = this.props.match.params.user_id;

                const result = await UserStore.updateDetails(values);

                if (result) {
                    return message.error(result);
                }

                message.success('修改成功');

                UserStore.setVisible();

                this.props.history.goBack();
            }
        });
    }

    public cancelSafeCode = () => {
        UserStore.setVisible();
    }

    public render() {
        return (
            <Spin spinning={UserStore.detailsLoading}>
                <Form className="user-edit-wraper" onSubmit={this.handleSubmit}>
                    <h2 className="edit-title">编辑资料</h2>

                    <div className="edit">
                        {this.state.formItems}
                        <FormItem style={{marginTop: 30}}>
                            <Button className="submit"
                                    size="large"
                                    type="primary"
                                    onClick={()=>{
                                        this.props.history.goBack();
                                    }}
                                    style={{marginRight: 30, width: 100}}
                            >
                                返回
                            </Button>
                            <Button className="submit"
                                    htmlType="submit"
                                    size="large"
                                    type="primary">提交修改</Button>
                        </FormItem>
                    </div>
                </Form>
                <SafeCodeModal
                    visible={UserStore.modalVisible}
                    confirmLoading={UserStore.detailsLoading}
                    handleOk={this.handleSafeCode}
                    handleCancel={this.cancelSafeCode}
                />
            </Spin>
        )
    }
}

export default withWrapper(Form.create()(Edit));